package cc.loach.homekit.app.homekit.settings.database;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.HashMap;
import java.util.Map;

import cc.loach.homekit.hap.framewok.HapDatabase;

public class HapDatabaseImpl implements HapDatabase {

    private static final String NAME = "HapDatabase";
    private final SharedPreferences preferences;

    public HapDatabaseImpl(Context context) {
        this.preferences = context.getSharedPreferences(NAME, Context.MODE_PRIVATE);
    }

    @Override
    public void clean() {
        synchronized (this) {
            preferences.edit().clear().apply();
        }
    }

    @Override
    public void put(String key, String value) {
        synchronized (this) {
            SharedPreferences.Editor editor = preferences.edit();
            editor.putString(key, value);
            editor.apply();
        }
    }

    @Override
    public void remove(String key) {
        synchronized (this) {
            SharedPreferences.Editor editor = preferences.edit();
            editor.remove(key);
            editor.apply();
        }
    }

    @Override
    public String get(String key) {
        synchronized (this) {
            return preferences.getString(key, null);
        }
    }

    @Override
    public Map<String, String> getAll() {
        synchronized (this) {
            Map<String, String> result = new HashMap<>();

            for (Map.Entry<String, ?> e : this.preferences.getAll().entrySet()) {
                if (e.getValue() instanceof String) {
                    result.put(e.getKey(), (String) e.getValue());
                }
            }

            return result;
        }
    }
}
